<template>
  <div id="gift-form">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm" size="small" v-loading="loading">
      <el-form-item label="礼包名称" prop="name">
        <p  v-if="typeStr === 'details'">{{ruleForm.name}}</p>
        <el-input v-model="ruleForm.name" maxlength="30" show-word-limit v-else></el-input>

      </el-form-item>
      <el-form-item label="礼包简称" prop="shortName">
        <p v-if="typeStr === 'details'">{{ruleForm.shortName}}</p>
        <el-input v-model="ruleForm.shortName" maxlength="8" show-word-limit v-else></el-input>
      </el-form-item>
      <el-form-item label="商品" prop="goodsList">
        <template v-if="ruleForm.goodsList.length !== 0">
          <template v-for="(it, index) in ruleForm.goodsList">
          <p v-if="typeStr === 'details'">{{it.goodsSkuName}} * {{it.num}}</p>
          <p v-else>
            <span class="goods-sku-name">{{it.goodsSkuName}}</span>
            <el-input-number v-model="ruleForm.goodsList[index].num" :min="1" size="mini" label="描述文字"></el-input-number>
            <el-link type="danger" @click="deleteGoods(it.goodsSkuId)"><i class="el-icon-delete"></i></el-link>
          </p>
          </template>
        </template>
        <el-link type="primary" @click="showDialog"  v-if="typeStr !== 'details'">新增<i class="el-icon-plus"></i></el-link>
      </el-form-item>
      <el-form-item :label="'轮播图（'+ ruleForm.images.length+ '/5）'" prop="images" class='images'>
        <upload-picture :limitNumber="5" :file-list="ruleForm.images" @getUrl="getImagesUrl" @handleRemove="removeImagesUrl" v-bind:class="[{'images-list' : ruleForm.images && ruleForm.images.length > 4}, {'details': rQuery.type === 'details'}]" />
        <p>建议上传1125*330px图片，每张上传大小不得超过2M,支持jpg、png格式</p>
      </el-form-item>
      <el-form-item label="详情" prop="detailImage" class='detail-image'>
        <upload-picture :limitNumber="5" :file-list="ruleForm.detailImage" @getUrl="getDetailsUrl" @handleRemove="removeDetailsUrl" v-bind:class="[{'detail-image-list' : ruleForm.detailImage && ruleForm.detailImage.length !== 0}, {'details': rQuery.type === 'details'}]"/>
        <p>每张上传大小不得超过5M,支持jpg、png格式</p>
      </el-form-item>
      <el-form-item label="价格" prop="price" class="price">
        <p  v-if="typeStr === 'details'">{{ruleForm.price}}元</p>
        <template v-else>
<!--          <el-input v-model="ruleForm.price" oninput="value=value.replace(/[^\d]/g,'')" class="pure-number"></el-input>元-->
<!--          <el-input v-model="ruleForm.price" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')" class="pure-number"></el-input>元-->
<!--          <el-input v-model="ruleForm.price" @keyup.native="ruleForm.price = checkValue(ruleForm.price,2)" class="pure-number"></el-input>元-->
          <el-input v-model="ruleForm.price" @input="ruleForm.price = checkValue(ruleForm.price,2)" class="pure-number"></el-input>元
        </template>
      </el-form-item>
      <el-form-item label="赠送积分" prop="points" class="price">
        <p  v-if="typeStr === 'details'">{{ruleForm.points}}</p>
        <el-input v-model="ruleForm.points" @input="ruleForm.points = checkValue(ruleForm.points,0)" class="pure-number" v-else></el-input>
      </el-form-item>
      <el-form-item label="佣金" prop="commission">
        <template v-if="typeStr === 'details'">
        <p v-for="(it, index) in ruleForm.commission">推荐第{{index + 1 }}个次{{ruleForm.commission[index]}}%，将获得{{ calcProfit(ruleForm.commission[index], ruleForm.price) }}元收益</p>
        </template>
        <template v-else>
        <p v-for="(it, index) in ruleForm.commission">推荐第{{index + 1 }}个次<el-input v-model="ruleForm.commission[index]" @input="ruleForm.commission[index] = checkValue(ruleForm.commission[index],2)" size="mini" class="pure-number"></el-input>%，将获得 {{ calcProfit(ruleForm.commission[index], ruleForm.price) }} 元收益</p>
        </template>
        <p><el-checkbox v-model="ruleForm.selfCommissionFlag" :disabled="typeStr === 'details' ">个人购买第1次后自己购买佣金归自己</el-checkbox></p>
      </el-form-item>

      <el-form-item label="礼包支付方式" prop="payTypeList">
        <el-checkbox-group v-model="ruleForm.payTypeList">
          <el-checkbox :label="it.dictName" name="type" v-for="(it, index) in dictionaries.gift_package_pay_type" :disabled="index !==0 || typeStr === 'details' "></el-checkbox>
<!--          <el-checkbox label="优惠券" name="type" disabled></el-checkbox>-->
<!--          <el-checkbox label="积分" name="type" disabled></el-checkbox>-->
        </el-checkbox-group>
      </el-form-item>
	  <el-form-item label="标签" prop="tagList" required>
	    <div class="labelbox" style="flex-wrap: wrap;">
			<div class="labelitem" style="margin-bottom: 10px;" v-for="(item,index) in seletedTag" :key="item.id">
				{{item.tagName}}
				<i v-if="typeStr !== 'details'" class="el-icon-circle-close labelicon" @click="deleteTag(index)"></i>
			</div>
			<el-button type="primary" style="margin-bottom: 10px;" @click="dialogVisible = true" v-if="typeStr !== 'details'">添加标签</el-button>
		</div>
	  </el-form-item>
      <el-form-item label="平台" prop="platformIds">
        <el-select v-model="ruleForm.platformIds" multiple :disabled="typeStr === 'details' " placeholder="请选择平台">
          <el-option
              v-for="item in platformListFilter"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="库存" prop="stock" class="sales">
        <p v-if="typeStr === 'details'">{{ruleForm.stock}}</p>
        <el-input v-model="ruleForm.stock" oninput="value=value.replace(/^(0+)|[^\d]+/g,'')" class="pure-number" v-else></el-input>
      </el-form-item>
      <el-form-item label="销量" prop="fakeSaleNum" class="sales">
        <p v-if="typeStr === 'details'">{{ruleForm.fakeSaleNum}}</p>
        <el-input v-model="ruleForm.fakeSaleNum" oninput="value=value.replace(/^(0+)|[^\d]+/g,'')" class="pure-number" v-else></el-input>
        <p v-if="typeStr !== 'details'">设置后，销量从设置的值递增</p>
      </el-form-item>
      <el-form-item label="真实销量" prop="saleNum">
        <p>{{ruleForm.saleNum}}</p>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="ruleForm.status" :disabled="typeStr === 'details'">
          <el-radio :label="it.dictName" v-for="it in dictionaries.enable_status"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="有效期" prop="validityTime" class="validity-time">
        <template v-if="typeStr === 'details'">
        <span v-for="it in ruleForm.validityTime">{{it}}</span>
        </template>
          <el-date-picker
              v-else
              v-model="ruleForm.validityTime"
              type="daterange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
          >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <template v-if="rQuery.type === 'details'">
<!--          <el-button @click="resetForm('ruleForm')">关闭</el-button>-->
        </template>
        <template v-else>
          <el-button @click="resetForm('ruleForm')">取消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')" :disabled="submitLoading">确认</el-button>
        </template>
      </el-form-item>
    </el-form>
    <!--========================== el-dialog =================================-->
    <el-dialog
        :title="dialog.title"
        :visible.sync="dialog.visible"
        :width="dialog.width"
        :append-to-body="true"
    >
      <el-transfer
        filterable :filter-method="filterMethod"
        v-model="chooseGoods" :data="goodsSkuDataList"
        :props="{ key: 'goodsSkuId', label: 'goodsSkuName' }"
        :titles="['商品列表', '已选列表']"
        class="transfer-gift-form"
      >
        <div slot-scope="{ option }">
          <span class="transfer-label" :title="option.goodsSkuName">{{ option.goodsSkuName }}</span>
      <!--    <el-input-number :min="1" :max="10" label="描述文字" size="mini"></el-input-number>-->
        </div>
      </el-transfer>
      <div class="dia-foot-but">
        <el-button @click="dialog.visible = false;seletedTag = []">取消</el-button>
        <el-button type="primary" @click="getGoodsSkuDataList()">确认</el-button>
      </div>
    </el-dialog>
    <!--=========================== el-dialog end================================-->
		<el-dialog
		  title="添加标签"
		  :visible.sync="dialogVisible"
		  append-to-body
		  width="50%">
		  <div class="loglabelbox">
		  	<div class="loglabeltopbox">
		  		<div class="labelitem" :style="{cursor:item.select?'not-allowed':'pointer'}" :class="[item.select?'selected':'notselected']" v-for="(item,index) in tagList" :key="item.id" @click="selectTagFn(index)">
		  			{{item.tagName}}
		  		</div>
		  	</div>
			<div class="circlebox">
				已选
				<div class="circle">
					{{seletedTag.length}}
				</div>
			</div>
			<div class="loglabeltopbox" style="border: none;">
				<div class="labelitem labelitemc"  v-for="(item,index) in seletedTag" :key="item.id">
					{{item.tagName}}
					<i class="el-icon-circle-close labelicon" @click="deleteTag(index)"></i>
				</div>
			</div>
		  </div>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="dialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
		  </span>
		</el-dialog>

  </div>
</template>

<script>
import uploadPicture from '@/components/upload/picture.vue'
import common from '../mixins/common'
export default {
  mixins: [common],
  name: 'GiftForm',
  components: { uploadPicture },
  props: {
    typeStr: {
      type: String,
      default: () => 'add' // add 添加  edit 编辑 details 查看详情
    },
    config: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      pickerOptions: {
        disabledDate (time) {
          // return time.getTime() <= Date.now()
        }
      },
	  dialogVisible: false,
      submitLoading: false,
      loading: false,
      goodsSkuDataList: [],
      dialog: { visible: false, title: '编辑', width: '700px', type: '', row: {}, batch: false },
      chooseGoods: [],
      ruleForm: {
        name: '', // 名称
        shortName: '', // 简称
        goodsList: [], // 商品列表
        images: [], // 轮播图 [{ url: '' }]
        detailImage: [], // 详情
        price: 0, // 价格
        points: 0, // 赠送的积分
        stock: 0, // 库存
        saleNum: 0, // 真实销量
        commission: [0, 0, 0], // 佣金
        selfCommissionFlag: false, // 复购佣金是否归本人 （0否1是）
        payTypeList: [], // 支付方式 字典：gift_package_pay_type
        platformIds: [], // 数据来源：/order/v1-2/platform/dataList
        fakeSaleNum: 0, // 初始销量
        status: '', // 状态值 字典：enable_status
        validityTime: [], // 有效期
        tagList: []// 标签
      },
      rules: {
        name: [
          { required: true, message: '请输入礼包名称', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
        ],
        shortName: [
          { required: true, message: '请输入礼包简称', trigger: 'blur' },
          { min: 1, max: 8, message: '长度在 1 到 8 个字符', trigger: 'blur' }
        ],
        goodsList: [{ type: 'array', required: true, message: '请选择商品', trigger: 'change' }],
        images: [{ type: 'array', required: true, message: '请上传轮播图', trigger: 'change' }],
        detailImage: [{ type: 'array', required: true, message: '请上传详情图片', trigger: 'change' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        points: [{ required: true, message: '请输入积分', trigger: 'blur' }],
        commission: [{ type: 'array', required: true, message: '请输入佣金', trigger: 'change' }],
        payTypeList: [{ type: 'array', required: true, message: '请至少选择一个支付方式', trigger: 'change' }],
        platformIds: [{ type: 'array', required: true, message: '请选择平台', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        validityTime: [{ type: 'array', required: true, message: '请选择日期', trigger: 'change' }]
      },
      rQuery: {},
	  tagList: [],
	  seletedTag: []
    }
  },
  computed: { // 计算属性
    calcProfit () {
      return function (value, price) {
        const priceNum = Number(price) || 0
        const valueNum = Number(value) || 0
        const profit = (parseInt(priceNum * valueNum) / 100).toFixed(2)
        return profit
      }
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const rQuery = route.query
        this.rQuery = rQuery
        console.log('rQuery', this.rQuery)
        this.$refs['ruleForm'].resetFields()
        this.$nextTick(_ => {
          if (rQuery.type === 'edit' || rQuery.type === 'details') {
            this.fetchData(rQuery.gid)
          } else {
            this.seletedTag = []
          }
		  this.getSelectTagData()
        })
      },
      immediate: true
      // deep: true
    },
    typeStr (val) {
      // console.log(val)
    }
  },
  mounted () {
    this.$nextTick(_ => {
      // console.log('mounted')
    })
  },
  created () {
    const rQuery = this.$route.query
    this.rQuery = rQuery
    if (rQuery.type !== 'add') { this.fetchData(rQuery.gid) }
    this.getMatrixSkuDataList() // 商品sku列表查询接口
    this.getSelectTagData()
  },
  methods: {
	  deleteTag (idx) {
		  this.tagList.forEach(item => {
		  	if (this.seletedTag[idx].id == item.id) {
          item.select = false
        }
		  })
		  this.seletedTag.splice(idx, 1)

		  this.ruleForm.tagList = this.seletedTag.map(item => {
			  return item.id
		  })
	  },
	  selectTagFn (idx) {
		  if (!this.tagList[idx].select) {
			  this.tagList[idx].select = !this.tagList[idx].select
			  this.seletedTag.push(this.tagList[idx])
			  this.ruleForm.tagList = this.seletedTag.map(item => {
			  			  return item.id
			  })
		  }
	  },
	  getSelectTagData () {
	  	this.$api.selectTagData({})
	  	.then(res => {
	  		// this.tagList = res.data;
          console.log()
	  		this.tagList = res.data.map(item => {
            return { tagName: item.tagName, id: item.id, select: false }
          })
	  	})
	  	.catch(err => {
	  		console.log(err)
	  	})
	  },
    fetchData (gid) {
      this.loading = true
      // this.$refs['ruleForm'].resetFields()
      const params = { id: gid }
      this.$api.matrixDetails(params).then((res) => {
        this.loading = false
        if (res.code === 0) {
		  this.seletedTag = res.data.tagList
		  this.tagList.forEach(item => {
		  	this.seletedTag.forEach(i => {
		  		if (i.id == item.id) {
		  			item.select = true
		  		}
		  	})
		  })
          Object.assign(this.ruleForm, res.data)
          /*
          this.infoForm.imageList.forEach(item => {
            if (item.url && item.url.indexOf('http://fenxiao.muruji.com/') !== 0) { item.url = this.ImgHttps + item.url }
          })
          */

          // 轮播图
          this.ruleForm.images = []
          const imagesArr = []
          res.data.images.forEach(it => {
            if (it.indexOf('http') !== 0) { it = this.ImgHttps + it }
            imagesArr.push({ url: it })
          })
          this.ruleForm.images = imagesArr
          console.log(this.ruleForm.images, 'this.ruleForm.images')

          // 详情图
          this.ruleForm.detailImage = []
          const detailImageData = []
          res.data.detailImage.forEach(item => {
            if (item.indexOf('http') !== 0) { item = this.ImgHttps + item }
            detailImageData.push({ url: item })
          })
          this.ruleForm.detailImage = detailImageData
          this.ruleForm.tagList = res.data.tagList.map(item => {
            return item.id
          })
          // if (res.data.detailImage.indexOf('http') !== 0) { res.data.detailImage = this.ImgHttps + res.data.detailImage }
          // detailImageArr.push({ url: res.data.detailImage })
          // this.ruleForm.detailImage = detailImageArr
          // console.log(res.data.detailImage, 'res.data.detailImage')
          // 佣金
          this.ruleForm.commission[0] = res.data.firstCommissionProportion
          this.ruleForm.commission[1] = res.data.secondCommissionProportion
          this.ruleForm.commission[2] = res.data.thirdCommissionProportion

          // 后续购买礼包佣金归自己 后续购买礼包佣金归自己。没有的话就是没佣金（0否1是）
          this.ruleForm.selfCommissionFlag = res.data.selfCommissionFlag === 1

          // 支付方式
          this.ruleForm.payTypeList = []
          const payTypeArr = []
          this.dictionaries.gift_package_pay_type.forEach(it => {
            res.data.payTypeList.forEach(item => {
              if (it.dictId === item) { payTypeArr.push(it.dictName) }
            })
          })
          this.ruleForm.payTypeList = payTypeArr

          // 平台
          this.ruleForm.platformIds = []
          const platformIdsArr = []
          res.data.platform.forEach(item => {
            platformIdsArr.push(Number(item.id))
          })
          this.ruleForm.platformIds = platformIdsArr

          // 状态
          this.dictionaries.enable_status.forEach(it => {
            if (res.data.status == it.dictId) {
              this.ruleForm.status = it.dictName
            }
          })

          // 有效期
          // this.ruleForm.validityTime[0] = res.data.validityEndTime
          // this.ruleForm.validityTime[1] = res.data.validityStartTime
          this.$set(this.ruleForm, 'validityTime', [res.data.validityStartTime, res.data.validityEndTime])
        }
      }).catch((err) => {
        this.loading = false
        console.log(err)
      })
    },
    checkValue (val, limit = 0) {
      val = val.replace(/[^\d.]/g, '') // 保留数字
      val = val.replace(/^00/, '0.') // 开头不能有两个0
      val = val.replace(/^\./g, '0.') // 开头为小数点转换为0.
      val = val.replace(/\.{2,}/g, '.') // 两个以上的小数点转换成一个
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.'); // 只保留一个小数点
      /^0\d+/.test(val) ? val = val.slice(1) : '' // 两位以上数字开头不能为0
      const str = '^(\\d+)\\.(\\d{' + limit + '}).*$'
      const reg = new RegExp(str)
      if (limit === 0) {
        // 不需要小数点
        val = val.replace(reg, '$1')
      } else {
        // 通过正则保留小数点后指定的位数
        val = val.replace(reg, '$1.$2')
      }
      return val
    },
    // 获取上传图片文件的链接
    getImagesUrl (getUrl) {
      console.log(getUrl)
      // if(e.mainImage && e.mainImage.indexOf("http://fenxiao.muruji.com/") !== 0){e.mainImage = this.ImgHttps + e.mainImage}
      this.ruleForm.images.push({ mainFlag: 0, url: this.ImgHttps + getUrl })
    },
    removeImagesUrl (url) {
      console.log('removeImagesUrl', url)
      const delIndex = this.ruleForm.images.findIndex(e => { return e.url == url })
      this.ruleForm.images.splice(delIndex, 1)
    },
    getDetailsUrl (getUrl) {
      // if(e.mainImage && e.mainImage.indexOf("http://fenxiao.muruji.com/") !== 0){e.mainImage = this.ImgHttps + e.mainImage}
      this.ruleForm.detailImage.push({ mainFlag: 0, url: this.ImgHttps + getUrl })
    },
    removeDetailsUrl (url) {
      console.log('removeDetailsUrl', url)
      const delIndex = this.ruleForm.detailImage.findIndex(e => { return e.url == url })
      this.ruleForm.detailImage.splice(delIndex, 1)
    },
    // 删除当前图片文件的链接（如果接受文件路径是数组时 使用此方法）
    handleRemove (url) {
      const delIndex = this.infoForm.imageList.findIndex(e => { return e.url == url })
      this.infoForm.imageList.splice(delIndex, 1)
    },

    // 商品sku列表查询接口
    getMatrixSkuDataList () {
      const params = {}
      /*
      const goodsSkuDataList = JSON.parse(sessionStorage.getItem('goodsSkuDataList'))
      if (goodsSkuDataList) {
        this.goodsSkuDataList = goodsSkuDataList
        return
      }
      */
      this.$api.matrixSkuDataList(params).then((res) => {
        if (res.code === 0) {
          console.log('num', res)
          res.data.forEach(item => {
            item['num'] = 1
          })
          this.goodsSkuDataList = res.data
          // sessionStorage.setItem('goodsSkuDataList', JSON.stringify(res.data))
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    filterMethod (query, item) {
      return item.goodsSkuName.indexOf(query) > -1
    },
    renderFunc (h, option) { // 目前 return 返回的使用了 jsx语法   :render-content="renderFunc"
      return <div><span on-dblclick={ () => this.dblclick(this.name, option)}>{ option.name }</span><h3>title</h3></div>
    },
    dblclick (modelV, option) { // 双击 穿梭
      // 简单的逻辑  如果不在 v-model值数组里面，则push，否则从数组中删除
      console.log(modelV, option)
    },
    showDialog () {
      const ruleFormGoodsList = this.ruleForm.goodsList
      const tempChooseGoods = []
      const goodsSkuDataList = this.goodsSkuDataList

      goodsSkuDataList.forEach(it => {
        ruleFormGoodsList.forEach(item => {
          if (it.goodsSkuId === item.goodsSkuId) { tempChooseGoods.push(it.goodsSkuId) }
        })
      })

      this.chooseGoods = tempChooseGoods
      const dialog = {
        visible: true,
        title: '选择商品',
        type: 'performanceStatistics',
        width: '600px',
        batch: false,
        subTitle: '(时间：2022年6月)'
      }
      this.dialog = dialog
      // console.log('showDetail 查看', this.dialog)
    },
    // 右侧列表元素变化时触发
    getGoodsSkuDataList () {
      // Array.from(new Set(this.skuFormConfig.attribute.concat(arr)))
      // Array.from(new Set(this.skuFormConfig.sourceAttribute.concat(goodsSpecList).filter(Boolean)))

      const tempChooseGoods = []
      const goodsSkuDataList = this.goodsSkuDataList
      const chooseGoods = this.chooseGoods
      goodsSkuDataList.forEach(it => {
        chooseGoods.forEach(item => {
          if (it.goodsSkuId === item) { tempChooseGoods.push(it) }
        })
      })
      const goodsList = [].concat(this.ruleForm.goodsList)
      this.ruleForm.goodsList = []
      // chooseGoods.forEach(item => { item['num'] = 1 })
      const tempArr = Array.from(new Set(goodsList.concat(tempChooseGoods)))
      const tempArr2 = this.unique(tempArr)
      console.log('getGoodsSkuDataList', tempArr2)
      this.ruleForm.goodsList = tempArr
      console.log('选中的数据有', this.ruleForm.goodsList)
      this.dialog.visible = false
	  this.seletedTag = []
    },
    // 删除商品
    deleteGoods (goodsSkuId) {
      const delIndex = this.ruleForm.goodsList.findIndex(e => { return e.goodsSkuId === goodsSkuId })
      this.ruleForm.goodsList.splice(delIndex, 1)
    },
    onHasOwnProperty (arr) {
      const obj = {}
      return arr.filter(function (item, index, arr) {
        return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)
      })
    },

    unique (arr) {
      for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (arr[i].goodsSkuNo === arr[j].goodsSkuNo) {
            arr.splice(j, 1)
            j--
          }
        }
      }
      return arr
    },

    submitForm (formName) {
      const rQuery = this.rQuery
      this.$refs[formName].validate((valid) => {
        const params = Object.assign({}, JSON.parse(JSON.stringify(this.ruleForm)))
        params.validityStartTime = params.validityTime[0] // 有效期开始
        params.validityEndTime = params.validityTime[1] // 有效期结束
        params.firstCommissionProportion = params.commission[0] // 佣金（第一次）
        params.secondCommissionProportion = params.commission[1] // 佣金（第二次）
        params.thirdCommissionProportion = params.commission[2] // 佣金（第三次）

        params.stock = Number(params.stock) // 库存

        // 后续购买礼包佣金归自己 后续购买礼包佣金归自己。没有的话就是没佣金（0否1是）
        params.selfCommissionFlag = this.ruleForm.selfCommissionFlag ? 1 : 0
        const detailImage = []
        // console.log(this.ruleForm.detailImage)
        this.ruleForm.detailImage.forEach(item => {
          detailImage.push(item.url)
        })
        params.detailImage = detailImage

        // params.detailImage = this.ruleForm.detailImage[0].url

        const tempImages = []
        this.ruleForm.images.forEach(item => {
          tempImages.push(item.url)
        })
        params.images = tempImages

        const tempPayTypeList = []
        this.dictionaries.gift_package_pay_type.forEach(it => {
          this.ruleForm.payTypeList.forEach(item => {
            if (it.dictName === item) { tempPayTypeList.push(it.dictId) }
          })
        })
        params.payTypeList = tempPayTypeList
        /*
        const tempPlatformIds = []
        console.log(this.ruleForm.platformIds)
        this.ruleForm.platformIds.forEach(item => {
          tempPlatformIds.push(Number(iitemd))
        })
        params.platformIds = tempPlatformIds
        */

        // 状态（1-启用，0-禁用）
        if (this.ruleForm.status.indexOf('启') > -1) {
          params.status = 1
        } else {
          params.status = 2
        }
        delete params.validityTime
        delete params.commission
        if (rQuery.type === 'add') {
          if (params.id) {
            delete params.id
          }
        }
        console.log(params)
        if (valid) {
          this.submitLoading = true
          this.$api.matrixAddOrUpdate(params).then((res) => {
            this.submitLoading = false
            if (res.code === 0) {
              console.log(res)
              this.onEmit('dialogFromData', { isGetData: true, visible: false })
              this.resetForm(formName)
              this.$notify({
                title: '成功',
                message: '操作成功!',
                type: 'success',
                duration: 3000
              })
            }
          }).catch((err) => {
            this.submitLoading = false
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
	  this.seletedTag = []
      const outputData = { data: 1, type: 2, isClose: true }
      this.$emit('dialogFromData', outputData)
      console.log(formName)
    },
    onEmit (emitFanStr, data, type) {
      const outputData = { data, type }
      this.$emit(emitFanStr, outputData)
      // console.log('onShowDetail - 查看', row)
    }
  }
}
</script>
<style lang="scss">
#gift-form:after, .transfer-gift-form:after, .dia-foot-but:after {
  clear: both;
  display: table;
  content: '';
}
#gift-form{
  .el-form-item{
    &>.el-form-item__label{
      font-weight: bold;
    }
    .goods-sku-name{
      width: 150px;
      display: inline-block;
    }
    .pure-number{
      margin: 0 10px;
      width: 120px;
    }
    .el-input-number{
      margin: 0 5px;
    }
  }

  .images .images-list .el-form > div > div:nth-child(2), .detail-image .detail-image-list .el-form > div > div:nth-child(2){
    //background-color:#ffcf79;
    //display:none;
  }
  .el-upload.details{
    // 查看模式删除按钮不展示
    .el-upload-list .el-upload-list__item-actions .el-upload-list__item-delete{
      //background-color: #FFBA00;
      display:none;
    }
    .el-form > div > div:nth-child(2){
      //background-color: #FFBA00;
      display:none;

    }
  }
  // .images .images-list, .detail-image .detail-image-list{
  //   .el-form > div > div:nth-child(2){
  //     background-color:#ffcf79;
  //     display:none;
  //   }
  // }

  .images .el-upload, .detail-image{
    width: 100%;
    .el-upload-list__item, .el-form > div > div{
      width: 90px;
      height: 90px;
      line-height: 90px;
      float: left;
      label{
        .el-icon-upload-success{
          float: right;
          margin-top: 10px;
          margin-right: 14px;
        }
      }
    }
    .el-form > div{
      .el-upload-list{
        float:left;
      }
    }
  }
  .price, .sales{
    .pure-number{
      margin-left: 0;
    }
  }
  .labelbox{
	  display: flex;
	  flex-wrap: nowrap;
	  .labelitem{
		  background-color: #F0F3FD;
		  padding: 2px 20px;
		  font-size: 14px;
		  color: #4168E7;
		  position: relative;
		  margin-right: 20px;
		  .labelicon{
			  color: #4168E7;
			  cursor: pointer;
			  position: absolute;
			  font-size: 16px;
			  right: -6px;
			  top: -6px;
		  }
	  }
  }

}

	.loglabelbox{
		  padding: 20px 0;
		  box-sizing: border-box;
		  border-top: 1px solid #D9D9D9;
		  border-bottom: 1px solid #D9D9D9;
		  .loglabeltopbox{
			  width: 100%;
			  display: flex;
			  flex-wrap: wrap;
			  flex-direction: row;
			  border-bottom: 1px dashed #CCCCCC;
			  .labelitem{
			  		  background-color: #F0F3FD;
			  		  padding: 2px 20px;
			  		  font-size: 14px;
			  		  color: #4168E7;
			  		  position: relative;
			  		  margin-right: 20px;
					  margin-bottom: 14px;
					  cursor: pointer;

			  }
			  .labelitemc{
				  .labelicon{
				  	color: #4168E7;
				  	cursor: pointer;
				  	position: absolute;
				  	font-size: 16px;
				  	right: -6px;
				  	top: -6px;
				  }
			  }
			  .notselected{
				  background-color: #4168E7;
				  color: #ffffff;
			  }
			  .selected{
			  	  background-color: #F3F3F3;
			  	  color: #333333;
			  }
		  }
		  .circlebox{
			  font-size: 16px;
			  color: #4168E7;
			  display: flex;
			  margin-top: 14px;
			  align-items: center;
			  margin-bottom: 14px;
			  .circle{
				  width: 20px;
				  height: 20px;
				  text-align: center;
				  line-height: 20px;
				  border-radius: 50%;
				  background-color: #4168E7;
				  color: white;
				  font-size: 12px;
				  margin-left: 10px;
				  box-sizing: border-box;
			  }
		  }
	}

.transfer-gift-form{
  .el-transfer-panel{
    width: calc((100% - 60px - 40px) / 2);
    float: left;
    &:first-child{
      .el-transfer-panel__item{
        .el-input-number{display: none}
      }
    }
    .el-transfer-panel__item{
      .transfer-label{
        width: 180px;
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
        -webkit-line-clamp: 1; /* 可以显示的行数，超出部分用...表示*/
        -webkit-box-orient: vertical;
      }
      .el-input-number{
        width: 100px;
        float: right;
        .el-input{

        }
      }
    }

  }
  .el-transfer__buttons{
    float: left;
    display: flex;
    flex-wrap: wrap;
    width: 60px;
    padding: 0 20px;
    margin-top: 100px;
    .el-button{
      margin-bottom: 10px;
    }
    .el-button + .el-button{
      margin-left: 0;
    }
  }
}
.dia-foot-but{
  width: 100%;
  float: left;
  text-align: center;
  margin: 20px auto;
}
.validity-time{
  span + span{
    margin-left:10px;
  }
}
</style>
